﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace HurricanePackage
{
    /// <summary>
    /// 单例类
    /// </summary>
    public abstract class SingletonForMono<T> : MonoBehaviour
        where T : SingletonForMono<T>
    {
        private static T g_instance;

        public static T Instance
        {
            //在awake阶段访问时
            get
            {
                if (g_instance == null)
                {
                    //在场景中根据游戏类型引用
                    g_instance = FindObjectOfType<T>();
                    if (g_instance == null)
                    {
                        new GameObject("Singleton of" + typeof(T)).AddComponent<T>();
                        //创建后会直接执行Awake()
                    }
                    else//确保初始化一次
                    {
                        g_instance.Init();
                    }
                }

                return g_instance;
            }
            private set { }
        }

        /// <summary>
        /// 子类成员的初始化
        /// </summary>
        protected abstract void Init();


        private void Awake()
        {
            //在awake以后的阶段访问时=》
            if (g_instance == null)
            {
                g_instance = this as T;
                Init();
            }
        }

        private void OnDestroy()
        {
            SingletonForMono<T>.Instance = (T)((object)null);
        }

        protected void OnApplicationQuit()
        {
            SingletonForMono<T>.Instance = (T)((object)null);
        }
    }
}
